<script>
import {getProductCommentApi, getProductDetailApi} from "@/api/product"
import defaultImg from '@/static/default-avatar.png'
import CountBox from '@/components/CountBox.vue'
import {addCartApi} from "@/api/cart"
import {getCartTotal, setCartTotal} from "@/utils/storage"
import loginConfirm from "@/mixins/loginConfirm.js"
import SafeBox from "@/components/SafeBox.vue"
import {urlResolve} from "@/utils/urlResolve"

export default {
  name: "Product",
  mixins: [loginConfirm], // 登录确认框方法
  components: {SafeBox, CountBox},
  data() {
    return {
      productId: '', // 商品id
      swipeImages: [], // 轮播图列表
      productDetail: {}, // 商品详情对象
      current: 0, // 当前轮播图索引
      productComment: [], // 商品评论
      productCommentTotal: 0, // 商品评论数量
      defaultImg,
      isShowPanel: false, // 上滑弹框是否显示
      titlePanel: '', // 上滑弹框名称
      buyCount: 1, // 购买数量(每一次选择的商品数量，还没下单)
      // cartTotal 其实只是为了显示个数字角标，放在本地存储就行
      // 最开始数量是 0，在当前页面点击加入购物车，变为 1，存入本地存储，并且修改 cartTotal 为 1，刷新从本地存储拿数据，数据不丢失
      // 在购物车页面，购物车数量+1，数量是3，存入本地存储，再次访问当前页面，从本地存储拿数据，cartTotal 为 3，完美
      cartTotal: getCartTotal(),
      content: '', // 后端传递的 html 代码，用于渲染商品描述
    }
  },
  onLoad(options) {
    // 通过路由参数获得商品id
    this.productId = options.id
    // 拿到商品 id 后发请求
    this.getProductDetail()
    this.getProductComment()
  },
  methods: {
    // 轮播图索引切换
    onChange(event) {
      this.current = event.detail.current
    },

    // 请求商品详情
    async getProductDetail() {
      const res = await getProductDetailApi(this.productId)
      this.swipeImages = res.data.detail.goods_images
      const detail = res.data.detail
      this.productDetail = detail
      // 使用正则替换修改后端传递的 html 代码里的 img 的宽度为 100%，并且设置为块级元素去掉图片间的缝隙
      this.content = detail.content.replace(/width:\s*\d+px;/gi, 'width: 100%; display: block;')
    },

    // 请求商品评论
    async getProductComment() {
      const res = await getProductCommentApi(this.productId, 3)
      this.productComment = res.data.list
      this.productCommentTotal = res.data.total
      // console.log(res)
    },

    // 弹出购物车或登录面板
    showPanel(str) {
      this.titlePanel = str
      this.isShowPanel = true
    },

    // 加入购物车
    async addCart() {
      // 如果弹出了登录确认框，说明没登录
      if (this.loginConfirm(this.addCart)) return

      // 有token就把商品加入购物车
      // 商品不同规格的id，就怕后端漏传参数
      const goodsSkuId = this.productDetail.skuList[0].goods_sku_id
      const res = await addCartApi(this.productId, goodsSkuId, this.buyCount)

      this.cartTotal = res.data.cartTotal
      setCartTotal(this.cartTotal) // 把购物车的商品总数存入本地存储
      uni.showToast({icon: "none", title: '加入购物车成功'})

      this.isShowPanel = false
    },

    // 跳转支付页
    goCheckout() {
      if (this.loginConfirm(this.goCheckout)) return

      const query = urlResolve({
        mode: 'buyNow',
        goodsId: this.productId,
        goodsSkuId: this.productDetail.skuList[0].goods_sku_id,
        goodsNum: this.buyCount
      })

      uni.navigateTo({url: `/pagesOrders/pages/Checkout/Checkout?${query}`})
    },
  },
  mounted() {
  },
  // 分享给朋友
  onShareAppMessage() {
    return {
      title: '智慧商城',
      path: `/pages/Product/Product?id=${this.productId}`
    }
  },
  // 分享到朋友圈
  onShareTimeline() {
  },
}
</script>

<template>
  <div class="product" style="padding-bottom: 50px;">
    <van-nav-bar placeholder fixed title="商品详情页" left-arrow @click-left="uni.navigateBack"/>

    <view class="swiper-box">
      <swiper :autoplay="true" :interval="3000" @change="onChange">
        <swiper-item v-for="image in swipeImages" :key="image.file_id">
          <image :src="image.external_url" alt=""/>
        </swiper-item>
      </swiper>

      <div class="custom-indicator">{{ current + 1 }} / {{ swipeImages.length }}</div>
    </view>
    <!-- 商品说明 -->
    <div class="info">

      <div class="title">
        <div class="price">
          <span class="now">￥{{ productDetail.goods_price_min }}</span>
          <span class="oldprice">￥{{ productDetail.goods_price_max }}</span>
        </div>
        <div class="sellcount">已售{{ productDetail.goods_sales }}件</div>
      </div>

      <div class="msg text-ellipsis-2">
        {{ productDetail.goods_name }}
      </div>

      <div class="service">
        <div class="left-words">
          <span><van-icon name="passed"/>七天无理由退货</span>
          <span><van-icon name="passed"/>48小时发货</span>
        </div>
        <div class="right-icon">
          <van-icon name="arrow"/>
        </div>
      </div>

    </div>

    <!-- 商品评价 -->
    <div class="comment">

      <div class="comment-title">
        <div class="left">商品评价 ({{ productCommentTotal }}条)</div>
        <div class="right">查看更多
          <van-icon name="arrow"/>
        </div>
      </div>

      <div class="comment-list">

        <div class="comment-item" v-for="item in productComment" :key="item.comment_id">
          <div class="top">
            <image :src="item.user.avatar_url || defaultImg" alt=""/>
            <div class="name">{{ item.user.nick_name }}</div>
            <van-rate allow-half :size="16" :value="item.score / 2" color="#ffd21e" void-icon="star"
                      void-color="#eee"/>
          </div>

          <div class="content text-ellipsis-2">
            {{ item.content }}
          </div>

          <div class="time">
            {{ item.create_time }}
          </div>
        </div>
      </div>

    </div>

    <!-- 商品描述 -->
    <div class="desc" v-html="content"></div>

    <!-- 底部 -->
    <div class="footer">

      <view class="footer-container">
        <div @click="uni.switchTab({url: '/pages/index/index'})" class="icon-home">
          <van-icon name="wap-home-o"/>
          <span>首页</span>
        </div>

        <div @click="uni.switchTab({url: '/pages/Cart/Cart'})" class="icon-cart">
          <!--这里使用的是 cartTotal > 0，其实实现了一个 cartTotal 从字符串转化为数字的隐式转化过程-->
          <span v-if="cartTotal > 0" class="num">{{ cartTotal }}</span>
          <van-icon name="shopping-cart-o"/>
          <span>购物车</span>
        </div>

        <div @click="showPanel('加入购物车')" class="btn-add">加入购物车</div>
        <div @click="showPanel('立刻购买')" class="btn-buy">立刻购买</div>
      </view>

      <!--tab 栏给个安全距离-->
      <SafeBox></SafeBox>
    </div>

    <!--页面底部安全距离-->
    <SafeBox></SafeBox>

    <!--弹框-->
    <van-action-sheet :show="isShowPanel" :title="titlePanel" @close="isShowPanel = false">
      <div class="panel">
        <div class="title">

          <div class="left">
            <image :src="productDetail.goods_image" alt=""/>
          </div>

          <div class="right">
            <div class="price">
              <span>¥</span>
              <span class="nowprice">{{ productDetail.goods_price_min }}</span>
            </div>

            <div class="count">
              <span>库存</span>
              <span>{{ productDetail.stock_total }}</span>
            </div>
          </div>
        </div>

        <div class="num-box">
          <span>数量</span>
          <CountBox v-model="buyCount"></CountBox>
        </div>

        <!--判断商品余量-->
        <div class="showbtn" v-if="productDetail.stock_total > 0">
          <!--如果 titlePanel 是立刻购买就加上类名 now ，按钮会变红-->
          <div @click="addCart" class="btn" v-if="titlePanel === '加入购物车'">加入购物车</div>
          <div @click="goCheckout" class="btn now" v-else-if="titlePanel === '立刻购买'">立刻购买</div>
        </div>

        <div class="btn-none" v-else>该商品已抢完</div>
      </div>
    </van-action-sheet>

  </div>
</template>

<style lang="less">
.swiper-box {
  position: relative;

  swiper {
    height: 375px;

    image {
      display: block;
      width: 100%;
      height: 100%;
    }
  }

  .custom-indicator {
    position: absolute;
    right: 10px;
    bottom: 10px;
    padding: 5px 10px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 15px;
  }
}

.info {
  padding: 10px;

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .now {
      color: #fa2209;
      font-size: 20px;
    }

    .oldprice {
      color: #959595;
      font-size: 16px;
      text-decoration: line-through;
      margin-left: 5px;
    }

    .sellcount {
      color: #959595;
      font-size: 16px;
    }
  }

  .msg {
    font-size: 16px;
    line-height: 24px;
    margin-top: 5px;
  }

  .service {
    display: flex;
    justify-content: space-between;
    line-height: 40px;
    margin-top: 10px;
    font-size: 16px;
    background-color: #fafafa;

    .left-words {
      span {
        margin-right: 10px;
      }

      .van-icon {
        margin-right: 4px;
        color: #fa2209;
      }
    }
  }
}

.comment {
  padding: 10px;

  .comment-title {
    display: flex;
    justify-content: space-between;

    .right {
      color: #959595;
    }
  }

  .comment-item {
    font-size: 16px;
    line-height: 30px;

    .top {
      height: 30px;
      display: flex;
      align-items: center;
      margin-top: 20px;

      image {
        width: 20px;
        height: 20px;
      }

      .name {
        margin: 0 10px;
      }
    }

    .time {
      color: #999;
    }
  }
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #fff;

  .footer-container {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    height: 55px;

    .icon-home, .icon-cart {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 14px;

      .van-icon {
        font-size: 24px;
      }
    }

    .icon-cart .num {
      position: absolute;
      z-index: 999;
      top: -2px;
      right: 0;
      border-radius: 50%;
      background-color: #ee0a24;
      min-width: 16px;
      padding: 0 4px;
      text-align: center;
    }

    .btn-add,
    .btn-buy {
      height: 36px;
      line-height: 36px;
      width: 120px;
      border-radius: 18px;
      background-color: #ffa900;
      text-align: center;
      color: #fff;
      font-size: 14px;
    }

    .btn-buy {
      background-color: #fe5630;
    }
  }
}

.panel {
  .title {
    display: flex;

    .left {
      image {
        width: 90px;
        height: 90px;
      }

      margin: 10px;
    }

    .right {
      flex: 1;
      padding: 10px;

      .price {
        font-size: 14px;
        color: #fe560a;

        .nowprice {
          font-size: 24px;
          margin: 0 5px;
        }
      }

    }
  }

  .num-box {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    align-items: center;
  }

  .btn, .btn-none {
    height: 40px;
    line-height: 40px;
    margin: 20px;
    border-radius: 20px;
    text-align: center;
    color: rgb(255, 255, 255);
    background-color: rgb(255, 148, 2);
  }

  .btn.now {
    background-color: #fe5630;
  }

  .btn-none {
    background-color: #cccccc;
  }

}
</style>
